

var urlList = new Array();


function pUrl(id,url){
    this.id = id;
    this.url = url;
}


$(function(){

    //关闭预加载动画
    okLoading.close($);

    //在获取页面信息是进行ajax访问获取第一页的数据
    $.ajax({
        url: "/selectPageByCondition",
        type: "POST",
        success: function (data) {
            //将获取的数组信息打印到body中
            addListToTable(data);
            console.log(data);//在控制台输出数据
        },
        error: function () {
            alert("查询失败！");
        }
    });

    //实现精确查询模态框的操作
    $("#userName").click(function(){
        var result = $("#userNameValue").val();
        if(result==0){
            $("#userName").css("background-color","#00C292");
            $("#userNameValue").val(1);
            $("#userNameDiv").slideDown(300);
        }else if(result==1){
            $("#userName").css("background-color","#B8C3C5");
            $("#userNameValue").val(0);
            $("#userNameDiv").slideUp(300);
        }
    });
    $("#userPwd").click(function(){
        var result = $("#userPwdValue").val();
        if(result==0){
            $("#userPwd").css("background-color","#00C292");
            $("#userPwdValue").val(1);
            $("#userPwdDiv").slideDown(300);
        }else if(result==1){
            $("#userPwd").css("background-color","#B8C3C5");
            $("#userPwdValue").val(0);
            $("#userPwdDiv").slideUp(300);
        }
    });
    $("#userSex").click(function(){
        var result = $("#userSexValue").val();
        if(result==0){
            $("#userSex").css("background-color","#00C292");
            $("#userSexValue").val(1);
            $("#userSexDiv").slideDown(300);
        }else if(result==1){
            $("#userSex").css("background-color","#B8C3C5");
            $("#userSexValue").val(0);
            $("#userSexDiv").slideUp(300);
        }
    });
    $("#userNick").click(function(){
        var result = $("#userNickValue").val();
        if(result==0){
            $("#userNick").css("background-color","#00C292");
            $("#userNickValue").val(1);
            $("#userNickDiv").slideDown(300);
        }else if(result==1){
            $("#userNick").css("background-color","#B8C3C5");
            $("#userNickValue").val(0);
            $("#userNickDiv").slideUp(300);
        }
    });
    $("#userMobile").click(function(){
        var result = $("#userMobileValue").val();
        if(result==0){
            $("#userMobile").css("background-color","#00C292");
            $("#userMobileValue").val(1);
            $("#userMobileDiv").slideDown(300);
        }else if(result==1){
            $("#userMobile").css("background-color","#B8C3C5");
            $("#userMobileValue").val(0);
            $("#userMobileDiv").slideUp(300);
        }
    });
    $("#userDate").click(function(){
        var result = $("#userDateValue").val();
        if(result==0){
            $("#userDate").css("background-color","#00C292");
            $("#userDateValue").val(1);
            $("#userDateDiv").slideDown(300);
        }else if(result==1){
            $("#userDate").css("background-color","#B8C3C5");
            $("#userDateValue").val(0);
            $("#userDateDiv").slideUp(300);
        }
    });
        //实现精确查询的AJAX
    $("#bestQuery").click(function(){
        var queryUser = new Object();
        if($("#userNameValue").val()==1){
            queryUser.username = $("#divName").val();
        }
        if($("#userPwdValue").val()==1){
            queryUser.password = $("#divPwd").val();
        }
        if($("#userSexValue").val()==1){
            queryUser.sex = $("#divSex").val();
        }
        if($("#userNickValue").val()==1){
            queryUser.nickname = $("#divNick").val();
        }
        if($("#userMobileValue").val()==1){
            queryUser.mobile = $("#divMobile").val();
        }
        if($("#userDateValue").val()==1){
            queryUser.startTime = $("#divStart").val();
            queryUser.endTime = $("#divEnd").val();
        }

        $.ajax({
            url: "/queryPageByUserInfo",
            type: "POST",
            data: queryUser,
            success: function (data) {
                //将获取的数组信息打印到body中
                addListToTable(data);
               // $("#pageOperation").css("display","none");
            },
            error: function () {
                alert("查询失败！");

            }
        });
    });

    //实现用户添加的模态框表单验证
    $('#user_name').blur(function(){
        var reg = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
        if(reg.test($("#user_name").val())){
            $("#usernameHint").css("color","#5FB878");
            $("#usernameJudge").val(1);
            return true;
        }else{
            $("#usernameHint").css("color","#FF0000");
            $("#usernameJudge").val(0);
            return false;
        }
    });
    $('#mobile').blur(function(){
        var reg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
        if(reg.test($("#mobile").val())){
            $("#mobileHint").css("color","#5FB878");
            $("#mobileJudge").val(1);
            return true;
        }else{
            $("#mobileHint").css("color","#FF0000");
            $("#mobileJudge").val(0);
            return false;
        }
    });
    $('#password').blur(function(){
        var reg = /^[a-zA-Z]\w{5,17}$/;
        if(reg.test($("#password").val())){
            $("#passwordHint").css("color","#5FB878");
            $("#passwordJudge").val(1);
            return true;
        }else{
            $("#passwordHint").css("color","#FF0000");
            $("#passwordJudge").val(0);
            return false;
        }
    });

    //实现单图片上传AJAX
    $("#pic").click(function () {
        $("#upload").click(); //隐藏了input:file样式后，点击头像就可以本地上传
        $("#upload").on("change",function(){
            var formData1 = new FormData();
            formData1.append('file', $('#upload')[0].files[0]);
            formData1.append("selectId", '0');
            console.log(formData1);
            $.ajax({
                url: "/upload",
                type: "POST",
                data: formData1,
                /**
                 *必须false才会自动加上正确的Content-Type
                 */
                contentType: false,
                /**
                 * 必须false才会避开jQuery对 formdata 的默认处理
                 * XMLHttpRequest会对 formdata 进行正确的处理
                 */
                processData: false,
                async: false,
                cache: false,
                success: function (data) {
                    $("#fileName").val(data);
                },
                error: function () {
                    alert("上传失败！");

                }
            });
            var objUrl = getObjectURL(this.files[0]) ; //获取图片的路径，该路径不是图片在本地的路径
            if (objUrl) {
                $("#pic").attr("src", objUrl) ; //将图片路径存入src中，显示出图片
            }
        });
    });


    $("#pic2").click(function () {
        $("#upload2").click(); //隐藏了input:file样式后，点击头像就可以本地上传
        $("#upload2").on("change",function(){
            var formData = new FormData();
            formData.append('file', $('#upload2')[0].files[0]);
            formData.append("selectId", $("#updateId").val());
            console.log(formData);
            $.ajax({
                url: "/upload",
                type: "POST",
                data: formData,
                async: false,
                cache: false,
                /**
                 *必须false才会自动加上正确的Content-Type
                 */
                contentType: false,
                /**
                 * 必须false才会避开jQuery对 formdata 的默认处理
                 * XMLHttpRequest会对 formdata 进行正确的处理
                 */
                processData: false,
                success: function (data) {
                    if(data==0){

                    }else{
                    $("#fileName2").val(data);}
                },
                error: function () {
                    alert("上传失败！");

                }
            });
            var objUrl = getObjectURL(this.files[0]) ; //获取图片的路径，该路径不是图片在本地的路径
            if (objUrl) {
                $("#pic2").attr("src", objUrl) ; //将图片路径存入src中，显示出图片
                var pictureUrl = objUrl;//将图片路径赋值
                console.log(1);
                urlList.push(new pUrl($("#updateId").val(),pictureUrl));

            }
        });
    });




    $("#addUser").click(function(){
        var user = new Object();
        /*    user.username = $("#user_name").val();
            user.password = $("#password").val();
            user.mobile = $("#mobile").val();*/
        user.level = $("#level").val();
        user.sex = $("#sex").val();
        var cl = $("#cardLevel").val();
        if(user.level=="member"){
            if(cl=="月卡"){
                user.cid = 1;
            }
            if(cl=="半年卡"){
                user.cid = 3;
            }
            if(cl=="年卡"){
                user.cid = 4;
            }
            if(cl=="两年卡"){
                user.cid = 5;
            }
            if(cl=="十年卡"){
                user.cid = 6;
            }
            user.myself = $("#fileName").val();
        }else{
            user.cid = 0;
            user.myself = "default.jpg";
        }
        /*alert($("#user_name").val()+user.cid+user.myself+$("#password").val()+$("#mobile").val());*/
        /*console.log(user);*/
        var usernameJudge = $("#usernameJudge").val();
        var mobileJudge = $("#mobileJudge").val();
        var passwordJudge = $("#passwordJudge").val();
        if(usernameJudge!="1"||mobileJudge!="1"|| passwordJudge!="1"){
            alert("请按条件输入正确信息！");
            return false;
        }
        var c = {"username":$("#user_name").val(),"password":$("#password").val(),
            "sex":user.sex,"mobile":$("#mobile").val(),
            "level":user.level,"cid":user.cid,"myself":user.myself};
        console.log(c);

        $.post("/addMember",{"username":$("#user_name").val(),"password":$("#password").val(),
            "sex":user.sex,"mobile":$("#mobile").val(),
            "level":user.level,"cid":user.cid,"myself":user.myself},function (data) {
            if(data==1){
                $("#info").css("display","block");
                $("#msg").html("<p>&nbsp;</p>" +
                    "<p style='font-size: 40px;'>成功</p>");
                window.setTimeout(function(){
                    $("#info").css("display","none");
                },2500);
            }else {
            alert(data);
            }
        });
    });



    $("#likeQuery").click(function(){
        $.ajax({
            url: "/selectPageByCondition",
            type: "POST",
            data: {"condition":$("#likeValue").val()},
            success: function (data) {
                //将获取的数组信息打印到body中
                addListToTable(data);
                console.log(data);
            },
            error: function () {
                alert("查询失败！");
            }
        });

    });


    $("#updateLevel").change(function(){
        var info =  $("#levelChange select").val();
        if(info=="大会员"){
            $("#memberInfo").slideDown(300);
        }
        else{
            $("#memberInfo").slideUp(300);
        }
    });

    $("#updateUserInfo").click(function () {
        var user = new Object();
        user.uid = $("#updateId").val();
        user.password = $("#updatePwd").val();
        user.sex = $("#sexChange select").val();
        user.mobile = $("#updateMobile").val();
        user.nickname = $("#updateNick").val();
        user.level =  $("#levelChange select").val();
        user.endMember = $("#endMember").val();
        user.myself = $("#fileName2").val();

        if(user.level=="普通用户"){
            delete user.endMember;
            delete user.myself;
            user.level = "user";
            $.post("/updateUserInfo",{"uid":user.uid,"password":user.password,
                "sex":user.sex,"mobile":user.mobile,"nickname":user.nickname,
                "level":user.level,"current":$("#updateCurrent").val()},function (data) {
                if(data.current==0){
                    alert("更新失败,手机号已被其他人注册了");
                    return false;
                }
                addListToTable(data);
            });
        }else{
            user.level = "member";
            $.post("/updateUserInfo",{"uid":user.uid,"password":user.password,
                "sex":user.sex,"mobile":user.mobile,"nickname":user.nickname,
                "level":user.level,"endMember":user.endMember,"myself":user.myself
                ,"current":$("#updateCurrent").val()},function (data) {
                if(data.current==0){
                    alert("更新失败,手机号已被其他人注册了");
                    return false;
                }
                addListToTable(data);
               // $("#imgId"+user.uid).attr("src",pictureUrl);

               /* for(var i =0;i<urlList.length;i++){
                    $("#imgId"+urlList[i].id).attr("src",urlList[i].url);
                }
                console.log(urlList);*/
            });
        }

    });

});

function choose(sex){
    if(sex==1){
        $("#man").css("background-color","#00C292");
        $("#woman").css("background-color","#B8C3C5");
        $("#sex").val("男");
    }else if(sex==0){
        $("#man").css("background-color","#B8C3C5");
        $("#woman").css("background-color","#00C292");
        $("#sex").val("女");
    }else if(sex==3){
        $("#user").css("background-color","#00C292");
        $("#member").css("background-color","#B8C3C5");
        $("#cardInfo").slideUp(300);
        $("#level").val("user");
    }else if(sex==4){
        $("#user").css("background-color","#B8C3C5");
        $("#member").css("background-color","#00C292");
        $("#cardInfo").slideDown(300);
        $("#level").val("member");

    }

}

function stopUpload(){
    $("#pic").attr("src","");
    $("#fileName").val("default.jpg");
}

function stopUpload2(){
    $("#pic2").attr("src","");
    $("#fileName2").val("default.jpg");
}

//建立一個可存取到該file的url
function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}


function addListToTable(data){
 //   $("#pageOperation").css("display","none");//解决精确查询翻页异常

    $("#one").text(data.current);//设定当前页码
    $("#pageEnd").val(data.pages);//设定总页数
    $("#userTable tr:not(:eq(0))").remove();//在添加数据前,先删除标题以外的内容
    $("#pages").text(data.pages);
    $("#total").text(data.total);
    for(var i=0;i<data.records.length;i++){
        //将records以js的形式添加到指定table中
        if(data.records.length==0){
            $("#userTable").append("<tr class='danger'><td>无数据</td></tr>");
            break;
        }
        if(data.records[i].level=="user"){
            data.records[i].level = "普通用户";
        }
        if(data.records[i].level=="member"){
            data.records[i].level = "大会员";
        }
        if(data.records[i].level=="大会员"){//用于区别会员和非会员
            $("#userTable").append("<tr class='success'><td>"
                +data.records[i].uid+ "</td><td>"
                +data.records[i].username+"</td><td>"
                +data.records[i].password+"</td><td>"
                +data.records[i].sex+"</td><td>"
                +"<img src='img/"+data.records[i].picture+"' style='width: 30px;height:30px;border-radius: 50%'>"+"</td><td>"
                +data.records[i].mobile+"</td><td>"
                +data.records[i].createTime+"</td><td>"
                +data.records[i].nickname+"</td><td>"
                +data.records[i].level+"</td><td>"
                +"<img id='imgId"+data.records[i].uid+"'src='img/"+data.records[i].myself+"' style='width: 30px;height:30px;border-radius: 50%'>"+"</td><td>"
                +"<button class='btn btn-primary' data-toggle='modal' data-target='#update' onclick='getUserInfoByUid("+data.records[i].uid+","+data.current+")'>更新</button>"+"</td><td>"
                +"<button class='btn btn-default' onclick='deleteUserByUid("+data.records[i].uid+","+data.current+")'>删除</button>"+
                "</td></tr>");
            continue;
        }
        $("#userTable").append("<tr><td>"
            +data.records[i].uid+ "</td><td>"
            +data.records[i].username+"</td><td>"
            +data.records[i].password+"</td><td>"
            +data.records[i].sex+"</td><td>"
            +"<img src='img/"+data.records[i].picture+"' style='width: 30px;height:30px;border-radius: 50%'>"+"</td><td>"
            +data.records[i].mobile+"</td><td>"
            +data.records[i].createTime+"</td><td>"
            +data.records[i].nickname+"</td><td>"
            +data.records[i].level+"</td><td>"
            +"<img id='imgId"+data.records[i].uid+"' src='img/"+data.records[i].myself+"' style='width: 30px;height:30px;border-radius: 50%'>"+"</td><td>"
            +"<button class='btn btn-primary' data-toggle='modal' data-target='#update' onclick='getUserInfoByUid("+data.records[i].uid+","+data.current+")'>更新</button>"+"</td><td>"
            +"<button class='btn btn-default' onclick='deleteUserByUid("+data.records[i].uid+","+data.current+")'>删除</button>"+
            "</td></tr>");
    }
    for(var i =0;i<urlList.length;i++){
        $("#imgId"+urlList[i].id).attr("src",urlList[i].url);
    }
}

function getUserInfoByUid(uid,current){
    $("#updateCurrent").val(current);
    $.post("/selectOne",{"uid":uid},function (data) {
        $("#updateId").val(data.uid);
        $("#updateName").val(data.username);
        $("#updatePwd").val(data.password);
        $("#sexChange select").val(data.sex);
        $("#updateMobile").val(data.mobile);
        $("#updateNick").val(data.nickname);
        $("#updateTime").val(data.createTime);
        if(data.level =="user"){
            $("#levelChange select").val("普通用户");
            $("#memberInfo").slideUp(300);
        }else{
            $("#levelChange select").val("大会员");
            $("#memberInfo").slideDown(300);
        }
        $("#endMember").val(data.endMember);
        $("#fileName2").val(data.myself);
        $("#pic2").attr('src', 'img/'+data.myself);
        for(var i =0;i<urlList.length;i++){
            if($("#updateId").val()==urlList[i].id){
                $("#pic2").attr('src', urlList[i].url);
            }
        }
    })
}



function deleteUserByUid(uid,current){
    if(confirm("确定删除该用户嘛？")){
        $.post("/deleteUserInfo",{"uid":uid,"current":current},function (data) {
            addListToTable(data);
        });
    }
}



//编写获取页面信息的函数，通过ajax实现json数据分解赋值
function nextPage(a){
    //获取当前的页面情况
    var pageNow = parseInt($("#one").text());//当前页码
    var pageEnd = $("#pageEnd").val();//总页数
   // alert(pageEnd);
    if((a==2&pageNow==1)||(a==3&pageNow==pageEnd)||(a==1&pageNow==1)||pageEnd==1){
        //如果当前页码为1则无法再往前翻一页，反之同理。
     //   alert(1);
        return false;
    }
    if(a==1){//首页 传入页码current=1
        $.post("/selectPageByCondition",{"current":1},function (data) {
            addListToTable(data);
        });
    }
    if(a==2){//上一页 current = current-1;
        $.post("/selectPageByCondition",{"current":pageNow-1},function (data) {
            addListToTable(data);
        });
    }
    if(a==3){//下一页current = current+1;
        $.post("/selectPageByCondition",{"current":pageNow+1},function (data) {
            addListToTable(data);
        });
    }
    if(a==0){//尾页 current = page;
        $.post("/selectPageByCondition",{"current":pageEnd},function (data) {
            addListToTable(data);
        });
    }
}
